import {XTP} from "../modules/api/xtp";

const MenuAPI = XTP.menu;

export const getMenuOperation = (path) => {
    //根据url获取相应的操作权限
    function operationsFun(allMenu, path) {
        let operations = "";
        const menuOperationCodes = [];
        const menuOperation = allMenu.find((menu) => menu.url === path);
        if (menuOperation) {
          menuOperation.operationList.map((op) => {
            menuOperationCodes.push(op.code);
          });
          operations = menuOperationCodes.join("|");
        }
        return operations;
    }

    return new Promise((resolve) => {
        const menuOperation = [];
        if (menuOperation.length === 0) {
            const Authorization = localStorage.getItem(window.TOKEN_KEY) || null;
            if(!Authorization){
                resolve({operation: null, oauth: false});
                return true;
            } else {
                let allMenu = [];
                //如果不存在已经存在的操作权限需要重新去数据库
                MenuAPI.listMenuWithOperationByUserId().then(({res}) => {
                    if(res.status && res.status !== 200){
                        resolve({operation: null, oauth: false});
                    }
                    if (res.data.code === 1) {
                        allMenu = res.data.data.allMenu;
                    }
                    sessionStorage.setItem("menu-operation", JSON.stringify(allMenu));
                    resolve({operation: operationsFun(allMenu, path), oauth: true});
                });
            }
        } else {
          resolve({operation: operationsFun(menuOperation, path), oauth: true});
        }
      });

};